package com.starblink.mine.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.inflater
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.extraOf
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigation
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef.MinePage
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.PersonInfoModified
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.home.databinding.FragmentNavMineBinding
import com.starblink.home.databinding.ItemMineRouteBinding
import com.starblink.home.databinding.ItemMineTitleBinding
import com.starblink.home.databinding.ItemSubStoreAddBinding
import com.starblink.home.databinding.ItemSubStoreEmptyBinding
import com.starblink.home.databinding.ItemSubWishlistChildBinding
import com.starblink.home.databinding.LayHomeOrMineSubStoreBinding
import com.starblink.home.databinding.LayMeBrandStoreBinding
import com.starblink.mine.ui.cells.MyServiceItemCell
import com.starblink.mine.ui.cells.MyServiceTitleCell
import com.starblink.mine.ui.cells.SubMineBottomCell
import com.starblink.mine.ui.cells.SubStoreEmptyCell
import com.starblink.mine.ui.cells.SubWishlistAddCell
import com.starblink.mine.ui.cells.SubWishlistMineCell
import com.starblink.mine.ui.cells.SubWishlistMineChildCell

class NavMineFragment : BaseTVMFragment<FragmentNavMineBinding, NavMineVM>() {
    private val range = CommUtils.dip2px(100)

    companion object {
        private const val TAG = "NavMineFragment"
        fun obtainFragment(): NavMineFragment {
            return NavMineFragment()
        }
    }

    private val subAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.subWishData.value!!).apply {
            addVhDelegate {
                SubWishlistMineChildCell(
                    mActivity,
                    ItemSubWishlistChildBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                SubWishlistAddCell(
                    ItemSubStoreAddBinding.inflate(it.inflater, it, false),
                    spmPageValue = SpmPageDef.MinePage
                ) {
                    navigation(path = RoutePage.Wishlist.WISHLIST_ENTRY)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            event = TrackEvent.elementClick.value,
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                MinePage,
                                SpmElementDef.Element_33088
                            ),
                            params = mapOf("name" to "my wishlist")
                        )
                    )
                }
            }
            addVhDelegate {
                SubStoreEmptyCell(
                    ItemSubStoreEmptyBinding.inflate(it.inflater, it, false)
                )
            }
        }
    }

    private val adapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.mList.value!!).apply {
            addVhDelegate {
                //My favourite stores
                SubWishlistMineCell(
                    mActivity,
                    LayHomeOrMineSubStoreBinding.inflate(it.inflater, it, false), subAdapter
                ) {
                    navigation(path = RoutePage.Wishlist.WISHLIST_ENTRY)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            event = TrackEvent.elementClick.value,
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                MinePage,
                                SpmElementDef.Element_33088
                            ),
                            params = mapOf("name" to "my wishlist")
                        )
                    )
                }
            }
            addVhDelegate {
                SubMineBottomCell(
                    mActivity,
                    LayMeBrandStoreBinding.inflate(it.inflater, it, false),
                    brandListener = {
                        navigationTo(RoutePage.Store.PAGE_MANAGE_BRAND) {
                            viewModel.subBrandData.value?.isNotEmpty()
                        }
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                event = TrackEvent.elementClick.value,
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    MinePage,
                                    SpmElementDef.Element_33088
                                ),
                                params = mapOf("name" to "brands")
                            )
                        )
                    },
                    storeListener = {
                        navigationTo(RoutePage.Store.PAGE_MY_MANAGE) {
                            viewModel.subStoreData.value?.isNotEmpty()
                                ?.let { it1 -> withBoolean(RoutePage.Store.FOLLOWED, it1) }
                        }
                        SpmTrackHandler.addSingleTrackData(
                            SkAntEntity(
                                event = TrackEvent.elementClick.value,
                                spmCnt = GTrackerAssistUtils.fetchElementValue(
                                    MinePage,
                                    SpmElementDef.Element_33088
                                ),
                                params = mapOf("name" to "stores")
                            )
                        )
                    })
            }
            addVhDelegate {
                //my service标题
                MyServiceTitleCell(
                    mActivity,
                    ItemMineTitleBinding.inflate(it.inflater, it, false)
                )
            }
            addVhDelegate {
                //my service列表项
                MyServiceItemCell(
                    mActivity,
                    ItemMineRouteBinding.inflate(it.inflater, it, false)
                )
            }
        }
    }


    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?,
    ): FragmentNavMineBinding {
        return FragmentNavMineBinding.inflate(inflater, container, false)
    }

    override fun initData() {
        eventListener()
        viewModel.initItemData()
    }

    override fun initView(view: View) {
        super.initView(view)
        // 初始化滑动效果
//        viewBinding.appbarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
////            Log.e(
////                TAG,
////                "appbarHeight:" + appBarLayout.height + " getTotalScrollRange:" + appBarLayout.totalScrollRange + " offSet:" + verticalOffset
////            )
////            if (Math.abs(verticalOffset) >= (appBarLayout.totalScrollRange)) {
//            if (Math.abs(verticalOffset) >= range) {
//                viewBinding.navMineHeadLayout.headerImg.alpha = 0f
//            } else {
//                var progress = 1 - (Math.abs(verticalOffset) / range.toFloat())
//                viewBinding.navMineHeadLayout.headerImg.alpha = progress
////                viewBinding.titleHeaderImg.alpha = 1 - progress
////                viewBinding.titleUserName.alpha = 1 - progress
//            }
//        })

        initTopView()
        initOtherView()

        //控制底部导航显示或隐藏
//        showOrHideNavBarAnim(this.javaClass.name, viewBinding.recyclerView)
    }

    override fun startObserve() {
        //获取订阅
        viewModel.initRefresh()
    }

    private fun eventListener() {
        //刷新mine的数据
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            updateUserInfo()
            startObserve()
        }
        //按钮刷新商品收藏
        FlowBus.with<FollowStoreEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) {
            viewModel.refreshWishlist()
        }
        //按钮刷新店铺订阅
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) {
//            viewModel.refreshStores()
            viewModel.initRefresh()
        }
        //按钮刷新品牌订阅
        FlowBus.with<FollowStoreEvent>(FlowConst.SUBSCRIBE_BRAND_EVENT).register(this) {
//            viewModel.refreshBrands()
            viewModel.initRefresh()
        }
        // 监听用户信息修改事件
        FlowBus.with<PersonInfoModified>(FlowConst.PERSON_INFO_MODIFIED_EVENT).register(this) {
            if (it.headImage != null) {
                setUserHeadImage(it.headImage)
            }
            if (it.username != null) {
                viewBinding.navMineHeadLayout.userName.text = it.username
            }
        }
        // 监听更新消息未读数量事件
        FlowBus.with<Boolean>(FlowConst.UPDATE_MESSAGE_UNREAD_COUNT_EVENT).register(this) {
            if (it) {
                SKLogger.e("dss", "UPDATE_MESSAGE_UNREAD_COUNT_EVENT")
//                viewModel.checkUserUnreadMessageExist()
            }
        }
    }

    /**
     * 初始化顶部视图，包括标题栏，用户信息等
     */
    private fun initTopView() {
        updateUserInfo()
        // 更新消息红点
        viewModel.unreadMessage.observe(this) {
            if (it) {
                viewBinding.titleMsgImg.badgeViewHelper.showCirclePointBadge()
            } else {
                viewBinding.titleMsgImg.badgeViewHelper.hiddenBadge()
            }
        }

        // 查看消息
        viewBinding.titleMsgImg.click {
//            // 埋点：站内信按钮
//            SpmTrackHandler.addSingleTrackData(
//                SkAntEntity(
//                    spmCnt = GTrackerAssistUtils.fetchElementValue(
//                        SpmPageDef.MinePage,
//                        SpmElementDef.HOME_MESSAGE_CLICK
//                    ),
//                    params = mapOf("status" to if (viewModel.unreadMessage.value == true) "1" else "0")
//                )
//            )
//            navigation(path = RoutePage.Message.MESSAGE_ACTIVITY)
        }

        // 编辑个人信息
//        viewBinding.titleHeaderImg.click {
//            LoginManager.navigationToEditPersonalInfo(mActivity)
//        }
        viewBinding.navMineHeadLayout.headerImg.click {
            LoginManager.navigationToEditPersonalInfo(mActivity)
        }

        viewBinding.navMineHeadLayout.rootLay.click {
            // 如果未登录，跳转登录页面
            if (!UserDataCenter.isLogin()) {
                navigationTo(url = RoutePage.Login.SING_IN)
            }
        }

        viewBinding.btnScan.trackData(
            element = SpmElementDef.MineScanCamera,
            page = SpmPageDef.MinePage,
            onlyHit = true
        )
        viewBinding.btnScan.setOnClickListener {
            navigationTo(RoutePage.Web.PAGE_GLOBAL_SCAN) {
                extraOf(RoutePage.Web.ARG_WHITE_LIST to true)
            }
        }
    }

    private fun updateUserInfo() {
        if (UserDataCenter.isLogin()) {
            viewBinding.navMineHeadLayout.userName.text = UserDataCenter.getAccountInfo()?.userName
            viewBinding.navMineHeadLayout.headerImg.visible()
            viewBinding.navMineHeadLayout.tvLogin.gone()
//            viewBinding.titleMsgImg.visible()
        } else {
            viewBinding.navMineHeadLayout.userName.text = "Sign in"
            viewBinding.navMineHeadLayout.headerImg.gone()
            viewBinding.navMineHeadLayout.tvLogin.visible()
//            viewBinding.titleMsgImg.gone()
        }

        setUserHeadImage(UserDataCenter.getAccountInfo()?.headImage)
//        viewBinding.navMineHeadLayout.userName.text = UserDataCenter.getAccountInfo()?.userName
    }

    /**
     * 初始化头部以下的控件
     */
    private fun initOtherView() {
        //获取订阅 这个写前面
        viewModel.subWishData.value = arrayListOf(1, "", "", "", "")
        viewModel.subWishData.observe(this) {
            subAdapter.notifyDataSetChanged()
        }
        viewModel.subStoreData.observe(this) {
            adapter.notifyDataSetChanged()
        }
        viewModel.subBrandData.observe(this) {
            adapter.notifyDataSetChanged()
        }

        //底部导航列表 订阅也在里边 所以也要一起notify
        viewBinding.recyclerView.layoutManager = LinearLayoutManager(context)
        viewBinding.recyclerView.setHasFixedSize(true)
        viewBinding.recyclerView.itemAnimator = null
        viewBinding.recyclerView.adapter = adapter
        adapter.notifyDataSetChanged()

        viewBinding.refresher.setOnRefreshListener {
            viewModel.initRefresh()
            viewBinding.refresher.finishRefresh(3000)
        }
    }

    /**
     * 设置用户头像
     */
    private fun setUserHeadImage(url: String?) {
        ImageUtils.loadImage(
            mContext,
            url,
            viewBinding.navMineHeadLayout.headerImg,
            ImageUtils.placeholderAvatarImage,
            ImageUtils.placeholderAvatarImage
        )
//        ImageUtils.loadImage(
//            mContext,
//            url,
//            viewBinding.titleHeaderImg,
//            ImageUtils.placeholderAvatarImage,
//            ImageUtils.placeholderAvatarImage
//        )
    }
}